/*
 * @Author: 麦冬果果
 * @Date: 2021-09-07 10:50:51
 * @LastEditTime: 2021-09-07 14:19:21
 * @LastEditors: 麦冬果果
 * @Description: 定义文件
 * @FilePath: /svc/src/app/hook/define.go
 * 可以输入预定的版权声明、个性签名、空行等
 */
package hook

import (
	"fastapi/src/app/define"

	"github.com/gogf/gf/container/garray"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

type HookEntity struct {
	FuncName string
	Style    string
	Param    interface{}
	Run      func(r *ghttp.Request)
}

var HookList = garray.New()

//检查方法名是否存在
func GetHookByName(funcName string) *HookEntity {
	var result *HookEntity
	for _, item := range HookList.Slice() {
		hook := item.(HookEntity)
		if hook.FuncName == funcName {
			result = &hook
			break
		}
	}
	return result
}

//修改参数
func EditHookParams(funcName string, params interface{}) {
	for index, item := range HookList.Slice() {
		hook := item.(HookEntity)
		if hook.FuncName == funcName {
			hook.Param = params
			HookList.Set(index, hook)
			break
		}
	}
}

func GetOneAppApiByNames(params g.Map) (result *define.AppApi, err error) {
	model := g.DB("default").Model("app_api").Safe()

	model = model.Where("gname", params["gname"])
	model = model.Where("ename", params["ename"])
	err = model.Struct(&result)
	return
}

//BEFORE_SERVE
func BeforeServer(r *ghttp.Request) {
	//设置接口值
	defaltHook := GetHookByName("getApi")
	defaltHook.Run(r)
	//验证参数

	apis := r.GetCtxVar("appApi")
	var appApi *define.AppApi
	gconv.Struct(apis, &appApi)

	if appApi.HookWay == "BEFORE_SERVE" {
		hook := GetHookByName(appApi.HookName)
		hook.Run(r)
	}
}

//AFTER_SERVE
func AfterServer(r *ghttp.Request) {
	apis := r.GetCtxVar("appApi")
	var appApi *define.AppApi
	gconv.Struct(apis, &appApi)
	if appApi.HookWay == "AFTER_SERVE" {
		hook := GetHookByName(appApi.HookName)
		hook.Run(r)
	}
}

//BEFORE_OUTPUT
func BeforeOutput(r *ghttp.Request) {
	apis := r.GetCtxVar("appApi")
	var appApi *define.AppApi
	gconv.Struct(apis, &appApi)

	if appApi.HookWay == "BEFORE_OUTPUT" {
		hook := GetHookByName(appApi.HookName)
		hook.Run(r)
	}
}

//AFTER_OUTPUT
func AfterOutput(r *ghttp.Request) {
	apis := r.GetCtxVar("appApi")
	var appApi *define.AppApi
	gconv.Struct(apis, &appApi)

	if appApi.HookWay == "AFTER_OUTPUT" {
		hook := GetHookByName(appApi.HookName)
		hook.Run(r)
	}
}
